<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" >
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button>批量操作<a-icon type="down" /></a-button>
      </a-dropdown>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon" />
        已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        项
        <a style="margin-left: 24px"  @click="onClearSelected">清空</a>
        <span style="float:right;">
          <a><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <col-setting v-if="colSettingList.length>0" :defColumns="colSettingList" @columnsSetting="columnsSetting" />
        </span>
      </div>
      <a-table
        size="middle"
        bordered
        rowKey="formDataId"
        :columns="getColumns"
        :data-source="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:getCheckboxProps}"
        @change="handleTableChange"
      >
        <template slot="switch" slot-scope="text">
          <a-switch :checked="text" :disabled="true" />
        </template>
        <template slot="action" slot-scope="text, record">
          <a v-if="record.status === 0 || record.status === 3" @click="startInstance(record)">提交流程</a>
          <a-divider v-if="record.status === 0 || record.status === 3" type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.status === 0 || record.status === 3">
                <a @click="handleEdit(record,false)">编辑</a>
              </a-menu-item>
              <a-menu-item v-if="record.status !== 0">
                <a  @click="handleHistory(record)">查看进度</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleEdit(record,true)">详情</a>
              </a-menu-item>
              <a-menu-item v-if="record.status === 0 || record.status === 3">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.formDataId)">
                  <a >删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-table>
    </div>
    <!-- 表单弹窗区域 -->
    <!-- <a-modal
      :title="kfbTitle"
      :width="800"
      :visible="desformApplyVisible"
      @ok="desformApplyHandleOk"
      @cancel="desformApplyHandleCancel"
    >
      <k-form-build ref="kfb" :value="formData" :disabled="disabledAll" />
    </a-modal> -->
    <j-modal
      width="80%"
      :title="kfbTitle"
      :visible.sync="desformApplyVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      @ok="desformApplyHandleOk"
      @cancel="desformApplyHandleCancel"
      :destroyOnClose="true"
    >
      <k-form-build ref="kfb" :value="formData" :disabled="disabledAll" />
    </j-modal>
    <task-model ref="taskModel" title="历史" :taskData="taskData" type="history"></task-model>
  </a-card>
</template>
<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import ColSetting from '@/components/custom/ColSetting'
import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
import { getAction } from '@/api/manage'
import { saveOrUpdate, startInstance } from '@/api/process'
import { getFlowFormDictData } from '@/api/dict'
import taskModel from '@/views/modules/task/model/TaskModel'
export default {
  name: 'ProcessList',
  components: {
    ColSetting,
    JSuperQuery,
    taskModel
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      fullscreen: false,
      switchFullscreen: true,
      kfbTitle: '新增',
      desformApplyVisible: false,
      disabledAll: false, // 表单禁用控制
      columns: [], // 页面表格列
      colSettingList: [], // 表格列设置
      seriaColumns: {
        title: '#',
        dataIndex: 'rowIndex',
        width: 40,
        align: 'center',
        fixed: 'left',
        customRender: (t, r, i) => {
          return i + 1
        }
      },
      statusColumns: {
        title: '状态',
        align: 'center',
        dataIndex: 'status',
        customRender: (text) => {
          if (text === 1) {
            return '处理中'
          } else if (text === 2) {
            return '已完成'
          } else if (text === 3) {
            return '已退回'
          } else {
            return '未提交'
          }
        }
      },
      actionColumns: {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
        width: 150,
        scopedSlots: { customRender: 'action' }
      },
      url: {
        list: '/activiti/formData/list',
        deleteBatch: '/activiti/formData/deleteBatch',
        delete: '/activiti/formData/delete',
        getKfdJson: '/activiti/form/getFormDeploymentByModelId' // 自定义表单查询
      },
      modelData: {}, // 流程数据
      formData: {}, // 流程表单设计器json
      taskData: {}, // 流程数据
      fieldList: [],
      id: '', // 流程id
      disableMixinCreated: true, // 禁止mixin自动加载
      desformDesignList: [], // 表单设计器组件list（排除布局组件）
      dynamicDataCode: {}, //
      dynamicDataCodeParam: [], // 需要查询的字典或表
      setDynamicDataAjax: {}// 查询的字典或表数据
    }
  },
  computed: {
    getColumns() {
      const columns = []
      columns.push(this.seriaColumns)
      if (this.desformDesignList.length <= 0) {
        return []
      }
      this.desformDesignList.forEach(item => {
        if (item.options.hidden) { // 排除已隐藏
          return false
        }
        const key = item.model ? item.model : item.key
        const column = {
          title: item.label,
          align: 'center',
          dataIndex: 'formData.' + key,
          columnsData: item
        }
        if (['switch', 'uploadImg'].indexOf(item.type) >= 0) { // 这几个类型的组件使用scopedSlots渲染
          column.scopedSlots = { customRender: item.type }
        }
        if (['select', 'radio'].indexOf(item.type) >= 0) { // 下拉框、单选框等渲染方法
          column.customRender = (t, r, i) => {
            const dynamic = column.columnsData.options.dynamic
            if (dynamic === 'static') {
              return this.getSelectText(item.options.options, t)
            } else if (dynamic === 'distal') {
              const dynamicKey = column.columnsData.options.distal.tableName
              return this.setDynamicDataAjax[dynamicKey] ? this.getSelectText(this.setDynamicDataAjax[dynamicKey], t) : ''
            } else if (dynamic === 'dict') {
              const dynamicKey = column.columnsData.options.dynamicKey
              return this.setDynamicDataAjax[dynamicKey] ? this.getSelectText(this.setDynamicDataAjax[dynamicKey], t) : ''
            }
          }
        }
        if (['checkbox'].indexOf(item.type) >= 0) { // 复选框等渲染方法
          column.customRender = (t, r, i) => {
            return t && t.length > 0 ? this.getCheckboxText(item.options.options, t) : ''
          }
        }
        columns.push(column)
      })
      columns.push(this.statusColumns)
      columns.push(this.actionColumns)
      this.colSettingList = JSON.parse(JSON.stringify(columns))
      return columns
    }
  },
  watch: {
    $route() {
      this.init()
    }
  },
  created() {
    this.init()
    this.queryParam.modelId = this.id
    this.loadData()
    this.initDictConfig()
  },
  methods: {
    init() {
      const id = this.$route.fullPath.replace('/processList/', '')
      if (!id) {
        this.$message.warning('未找到需要查询的流程ID')
        return false
      }
      this.id = id
      this.getFormJson(id).then((res) => { // 查询已有表单设计器
        if (res.success) {
          this.modelData = res.result
          this.formData = res.result ? JSON.parse(res.result.htmlJson) : []
          this.desformDesignList = this.getFormList(this.formData.list)
          this.setSuperQueryFieldList()
          this.getDynamicDataCode(this.formData.list)
          getFlowFormDictData({ jsonStr: JSON.stringify(this.dynamicDataCodeParam) }).then(res => {
            this.setDynamicDataAjax = res.result
          })
        } else {
          this.$message.warning(res.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()// 查询条件
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.dataSource.forEach((item) => {
            item.formData = JSON.parse(item.formData)
          })
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getFormJson(id) { // 获取表单设计器json
      return getAction(this.url.getKfdJson, { modelId: id })
    },
    columnsSetting(checkedValues) { // 根据配置的colunms 渲染表格
      this.columns = this.colSettingList.filter(item => {
        if (checkedValues.indexOf(item.dataIndex) >= 0) {
          return true
        }
        return false
      })
    },
    getFormList(data) { // 根据表单设计器json获取组件（不包含布局容器）
      let formList = []
      data.forEach(item => {
        if (item.model && item.type !== 'batch') {
          formList.push(item)
        } else if (item.type === 'card') {
          formList = formList.concat(this.getFormList(item.list))
        } else if (item.type === 'grid') {
          item.columns.forEach(element => {
            formList = formList.concat(this.getFormList(element.list))
          })
        } else if (item.type === 'table') {
          item.trs.forEach(tr => {
            tr.tds.forEach(td => {
              formList = formList.concat(this.getFormList(td.list))
            })
          })
        }
      })
      return formList
    },
    setSuperQueryFieldList() { // 设置高级查询组件数据
      const superQueryFieldList = []
      this.desformDesignList.forEach(item => {
        const obj = {
          type: 'string',
          value: item.model,
          text: item.label
        }
        if (item.type === 'number' || item.type === 'date') {
          obj.type = item.type
        } else if (item.type === 'time') {
          obj.type = 'datetime'
        } else if (item.type === 'user') {
          obj.type = 'select-user'
        } else if (item.type === 'dept') {
          obj.type = 'select-depart'
        } else if (item.type === 'select') {
          obj.type = 'select'
          obj.options = item.options.options
        }
        superQueryFieldList.push(obj)
      })
      this.fieldList = superQueryFieldList
    },
    getSelectText(option, val) {
      let text
      option.forEach(item => {
        if (item.value === val) {
          text = item.label || item.text
          return false
        }
      })
      return text
    },
    getCheckboxText(option, val) {
      const text = []
      option.forEach(item => {
        if (val.indexOf(item.value) >= 0) {
          text.push(item.label)
        }
      })
      return text.join()
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: !(record.status === 0 || record.status === 3) // Column configuration not to be checked
        }
      }
    },
    handleEdit(record, disabled) { // 编辑流程
      this.disabledAll = disabled
      this.desformApplyVisible = true
      this.taskData = record
      this.kfbTitle = '编辑'
      this.$nextTick(() => {
        this.$refs.kfb.setData(record.formData)
      })
    },
    handleAdd() { // 新增流程
      if (!this.modelData.processDefinitionId) {
        this.$message.warning('请发布流程再新增')
        return false
      }
      this.disabledAll = false
      this.kfbTitle = '新增'
      this.desformApplyVisible = true
    },
    async desformApplyHandleOk() { // 流程表单保存
      try {
        const formData = await this.$refs.kfb.getData()
        if (!this.modelData.processDefinitionId) {
          this.$message.warning('请先发布流程')
          return false
        }
        const res = await saveOrUpdate({
          modelId: this.modelData.modelId,
          formId: this.modelData.id,
          processDefinitionId: this.modelData.processDefinitionId,
          formData: JSON.stringify(formData),
          id: this.taskData.formDataId
        })
        if (res.success) {
          this.desformApplyVisible = false
          this.$message.success('保存成功')
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    desformApplyHandleCancel() { // 流程弹窗取消
      this.desformApplyVisible = false
    },
    startInstance(item) { // 提交流程
      startInstance({
        modelId: item.modelId,
        formDataId: item.formDataId,
        processDefinitionId:item.processDefinitionId
      }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    getDynamicDataCode(list) { // 获取表单设计器需要查询的字典
      const that = this
      list.forEach(function(item, i) {
        const dynamic = item.options.dynamic
        if (item.options && (dynamic === 'distal' || dynamic === 'dict') && !that.dynamicDataCode[dynamic]) {
          if (dynamic === 'distal') {
            that.dynamicDataCodeParam.push({
              type: 'table',
              value: item.options.distal.value,
              label: item.options.distal.label,
              code: item.options.distal.tableName
            })
          } else {
            that.dynamicDataCodeParam.push({
              type: 'dict',
              code: item.options.dynamicKey
            })
          }
          that.dynamicDataCode[dynamic] = true
        }
        if (item.list) {
          that.getDynamicDataCode(item.list)
        } else if (item.columns) {
          item.columns.forEach(column => {
            column.list && that.getDynamicDataCode(column.list)
          })
        }
      })
    },
    handleHistory(data) { // 点击查看进度
      this.taskData = data
      this.$refs.taskModel.editModalVisible = true
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
  .j-table-slot-view{
    font-size: 12px;
    font-style: italic;
  }
  .j-table-slot-view img {
    max-width: 80px;
    max-height: 25px;
  }
</style>
